package com.panpass.idempotent.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author panpass
 * @version 1.0.0
 */
@Slf4j
public class RedisHelper {
    private final StringRedisTemplate redisTemplate;

    public RedisHelper(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取锁
     *
     * @param key 锁key
     * @param expire 过期时间
     * @param timeUnit 时间单位
     * @return 是否获取成功
     */
    public boolean trySet(String key, long expire, TimeUnit timeUnit) {
        try {
            // setIfAbsent等同于SETNX命令
            // 设置成功返回true，key已存在返回false
            Boolean success = redisTemplate.opsForValue()
                .setIfAbsent(key, "1", expire, timeUnit);
            return success != null && success;
        } catch (Exception e) {
            log.error("Redis set error, key:{}", key, e);
            return false;
        }
    }

    /**
     * 删除key
     *
     * @param key 待删除的key
     */
    public void delete(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("Redis delete error, key:{}", key, e);
        }
    }
}